package org.meichao.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.meichao.config.vo.DataSourceEnum;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * mybatis配置
 */
@Configuration
@AutoConfigureAfter({DataSourceConfig.class})
@MapperScan(basePackages = {"org.meichao.*.dao"})
public class MybatisConfig {

    private static Logger logger = LoggerFactory.getLogger(MybatisConfig.class);

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSourceProxy")
                                                           DataSourceProxy dataSourceProxy) throws Exception {
        logger.info("-----------sqlSessionFactory init----------");
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        return sqlSessionFactoryBean.getObject();
    }


    /**
     *  @Qualifier 指定了哪个实现类才是我们需要加载的类，用name来确定
     * @param writeDataSource
     * @param readDataSource
     * @return
     */
    @Bean
    public DataSourceProxy dataSourceProxy(@Qualifier("writeDataSource") DataSource writeDataSource,
                                           @Qualifier("readDataSource") DataSource readDataSource){
        logger.info("-----------dataSourceProxy init----------");
        Map<Object,Object> targetDataSource = new HashMap<>();
        targetDataSource.put(DataSourceEnum.write.getType(), writeDataSource);
        targetDataSource.put(DataSourceEnum.read.getType(), readDataSource);

        DataSourceProxy dataSourceProxy = new DataSourceProxy();
        //设置默认的数据源
        dataSourceProxy.setDefaultTargetDataSource(writeDataSource);
        //设置数据源
        dataSourceProxy.setTargetDataSources(targetDataSource);
        return dataSourceProxy;
    }

}
